package com.ad.pet.app.account.order;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ad.pet.DaggerMainActivityCompent;
import com.ad.pet.Logger;
import com.ad.pet.R;
import com.ad.pet.app.RxDisposable;
import com.ad.pet.app.account.adapter.OrderDetailGoodAdapter;
import com.ad.pet.app.account.order.fragment.OrderStatusContract;
import com.ad.pet.app.account.order.fragment.OrderStatusPresenter;
import com.ad.pet.common.data.http.BusCall;
import com.ad.pet.common.data.utils.ui.DialogUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.events.RxBus;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.ui.activity.AppToolbarActivity;
import com.ad.pet.constant.Constant;
import com.ad.pet.models.remote.PayResult;
import com.ad.pet.models.remote.Wxpay;
import com.ad.pet.models.remote.account.order.BigOrder;
import com.ad.pet.models.remote.account.order.OrderType;
import com.ad.pet.ui.MaxRecyclerView;
import com.ad.pet.ui.PayChoseDialog;
import com.ad.pet.wxapi.PayContract;
import com.ad.pet.wxapi.PayPresenter;
import com.ad.pet.wxapi.WXPayUtils;
import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;

import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.android.schedulers.AndroidSchedulers;

/**
 * 18601668937
 * 商品包裹详情页
 * Created by SEELE on 2019/2/15.
 */

public class PacketDetailActivity extends AppToolbarActivity implements OrderStatusContract.View, PayContract.View {


    @BindView(R.id.iv_status)
    ImageView ivStatus;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_reciver)
    TextView tvReciver;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.recyelr_good)
    MaxRecyclerView recyelrGood;
    @BindView(R.id.tv_good_fee)
    TextView tvGoodFee;
    @BindView(R.id.tv_ship_fee)
    TextView tvShipFee;
    @BindView(R.id.tv_count)
    TextView tvCount;
    @BindView(R.id.tv_order_number)
    TextView tvOrderNumber;
    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;
    @BindView(R.id.tv_kefu)
    TextView tvKefu;
    @BindView(R.id.tv_wuliu)
    TextView tvWuliu;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    @Inject
    RxDisposable mRxDisposable;
    PayChoseDialog payChoseDialog;
    private OrderDetailGoodAdapter orderDetailGoodAdapter;
    @Inject
    PayPresenter mPayPresenter;
    @Inject
    OrderStatusPresenter mOrderStatusPresenter;
    private BigOrder bigOrder1;
    private String pgId;

    private int payType;

    static final int SDK_PAY_FLAG = 1;
    private Handler deliver = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG:
//                    String resault = msg.obj.toString();
//                    LogUtils.e("pay_resault",resault);
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    String notifyUrl = payResult.getNotifyUrl();
                    // 判断resultStatus 为9000则代表支付成功
                    Logger.e("result_alipay:" + resultInfo + "|" + resultStatus + "|" + notifyUrl);
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        mOrderStatusPresenter.getGoodOrderDetail(pgId);
                        ToastUtil.getToastUtil().showShort(getString(R.string.pay_success));

                        RxBus.getDefault().post("confim_success");
//                        finish();
//                        RxBus.getDefault().post(new Events.PayStatusCallback(notifyUrl, "alipay", resultInfo));
                    } else {//支付失败
                        ToastUtil.getToastUtil().showShort(getString(R.string.pay_failed));

                    }
                    break;
            }
        }
    };

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        mToolbar.setTitle("商品详情");

    }

    @Override
    protected int contentLayout() {
        return R.layout.activity_packet_detail;
    }

    @Override
    protected void clickRetry(View v) {

    }

    @Override
    protected void initViews() {
        mPayPresenter.onCreate(this);
        payChoseDialog = new PayChoseDialog(mActivity, R.style.custom_dialog_style,true);
        pgId = getIntent().getStringExtra(Constant.PG_ID);
        mOrderStatusPresenter.onCreate(this);
        mOrderStatusPresenter.getGoodOrderDetail(pgId);

        recyelrGood.setLayoutManager(new LinearLayoutManager(this));
        orderDetailGoodAdapter = new OrderDetailGoodAdapter(null);
        recyelrGood.setAdapter(orderDetailGoodAdapter);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvents() {
        payChoseDialog.setOnGetPayWay(new PayChoseDialog.OnGetPayWay() {


            @Override
            public void getPayWay(int way) {
                payType = way;
                String sendType = payType == 1 ? "1" : payType==0?"2":"5";
                mPayPresenter.upPayresult(bigOrder1.getOrder_id(), sendType);

            }
        });
        tvKefu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bigOrder1 != null) {
                    DialogUtil.createDialog(mActivity, "", "是否拨打"+bigOrder1.getLive_store_tel()+"?", "确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            call_phone(bigOrder1.getLive_store_tel());
                        }
                    }).show();

                }
            }
        });

        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("0".equals(bigOrder1.getOrder_status())) {
                    payChoseDialog.show();
                } else {
                    DialogUtil.createDialog(mActivity, "", "是否确认收货?", true, "取消", null, "确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mOrderStatusPresenter.confirmRecive(bigOrder1.getOrder_id());
                        }
                    }).show();
                }
            }
        });
        tvWuliu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtil.createDialog(mActivity, "", "是否取消订单?", true, "取消", null, "确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mOrderStatusPresenter.cancelOrder(bigOrder1.getOrder_id());
                    }
                }).show();
            }
        });
        mRxDisposable.add(RxBus.getDefault().toObservable(String.class)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new BusCall<String>() {
                    @Override
                    public void call(String webTitle) {
                        if ("confim_success".equals(webTitle)) {

                                    mOrderStatusPresenter.getGoodOrderDetail(pgId);



                        }
                    }
                }));
//        mRxDisposable.add(RxBus.getDefault().toObservable(Events.PayStatusCallback.class)
//                .observeOn(AndroidSchedulers.mainThread()).subscribe(new BusCall<Events.PayStatusCallback>() {
//                    @Override
//                    public void call(Events.PayStatusCallback webTitle) {
//                        if ("weixin_app".equals(webTitle.paytype)) {
//                            RxBus.getDefault().post("confim_success");
//                        }
//                    }
//                }));
    }

    @Override
    public void initInject() {
        DaggerMainActivityCompent.builder().applicationComponent(getApplicationComponent())

                .activityModule(getActivityModule()).build().inject(this);
    }

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void error(String msg) {
//        ToastUtil.getToastUtil().showShort(msg);
    }

    @Override
    public void error(int code, String msg) {
//        ToastUtil.getToastUtil().showShort(msg);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public void getPendingSuccess(List<BigOrder> bigOrder) {

    }

    @Override
    public void getPacketInfoSuccess(BigOrder bigOrder) {

    }

    @Override
    public void getOrderStatusSuccess(List<BigOrder> orderStatuses) {

    }

    @Override
    public void cancelOrderSuccess() {
        RxBus.getDefault().post("confim_success");
        ToastUtil.getToastUtil().showShort("取消订单成功");
    }

    @Override
    public void confirmOrderSuccess() {
        RxBus.getDefault().post("confim_success");
        ToastUtil.getToastUtil().showShort("确认收货成功");
    }

    @Override
    public void getGoodOrderDetailSuccess(BigOrder bigOrder) {

        mStatusLayoutManager.showContent();
        bigOrder1 = bigOrder;
        if (tvReciver!=null){
        tvReciver.setText(bigOrder.getReceiver_name());}
        tvPhone.setText(bigOrder.getReceiver_mobile());
        tvAddress.setText(bigOrder.getProvince_name() + bigOrder.getCity_name() + bigOrder.getDistrict_name() + bigOrder.getReceiver_address());
        orderDetailGoodAdapter.setNewData(bigOrder.getOrder_goods_list());
        tvGoodFee.setText("商品总价:￥" + bigOrder.getGoods_money());
        tvCount.setText("￥" + bigOrder.getOrder_money());
        tvOrderNumber.setText(bigOrder.getOrder_no());
        tvOrderTime.setText(bigOrder.getCreate_time());
        switch (bigOrder.getOrder_status()) {
            case "0":
                tvStatus.setText("待付款");
                tvWuliu.setVisibility(View.VISIBLE);
                tvWuliu.setText("取消订单");
                tvConfirm.setText("立即付款");
                ivStatus.setImageResource(R.drawable.ic_order_waitingpay);
                break;
            case "1":
                tvStatus.setText("买家已付款");
                ivStatus.setImageResource(R.drawable.ic_wuliu);
                tvWuliu.setVisibility(View.GONE);
                tvConfirm.setVisibility(View.GONE);
                break;
            case "2":
                tvStatus.setText("商家已发货");
                ivStatus.setImageResource(R.drawable.ic_order_waiting_send_good);
                break;
            case "4":
                tvStatus.setText("交易成功");
                tvConfirm.setVisibility(View.GONE);
                ivStatus.setImageResource(R.drawable.ic_order_waiting_over);
                break;
            case "5":
                tvStatus.setText("已关闭");
                ivStatus.setImageResource(R.drawable.ic_order_waiting_closer);
                tvWuliu.setVisibility(View.GONE);
                tvConfirm.setVisibility(View.GONE);
                break;
            case "-1":
                break;
        }
    }

    @Override
    public void myAppointListSuccess(List<OrderType> list) {

    }

    @Override
    public void cancelAppointListSuccess() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    public void call_phone(String phone) {


        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) this, Manifest.permission.CALL_PHONE)) {

                Toast.makeText(this, "请授权！", Toast.LENGTH_LONG).show();

                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", this.getPackageName(), null);
                intent.setData(uri);
                this.startActivity(intent);
            } else {
                ActivityCompat.requestPermissions((Activity) this, new String[]{Manifest.permission.CALL_PHONE}, 1);
            }
        } else {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_CALL);
            intent.setData(Uri.parse("tel:" + phone));
            this.startActivity(intent);
        }

    }

    @Override
    public void upPayresultSuccess(PayResult payResult) {

        if (payType == 1) {

            WXPayUtils wxPayUtils = new WXPayUtils(mActivity);
            if (wxPayUtils.isWxAppInstalledAndSupported()) {


                Wxpay wxpay = new Wxpay(payResult.getAppid(), payResult.getPartnerid(), payResult.getPrepay_id(), payResult.getNonce_str(), payResult.getTimestamp(), payResult.getPackageq(), payResult.getSign(), "notify_url");
                wxPayUtils.doPay(new Gson().toJson(wxpay));
                Logger.d("jsonString--->" + new Gson().toJson(wxpay));
            }
        } else if (payType == 0) {
            final String orderInfo = payResult.getAli_pay_str();   // 订单信息

            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    PayTask alipay = new PayTask(mActivity);
                    Map<String, String> result = alipay.payV2(orderInfo, false);
//                    result.put("notify_url", payUrl.getNotify_url());
                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    deliver.sendMessage(msg);
                }
            };
            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        }else {
            mOrderStatusPresenter.getGoodOrderDetail(pgId);
            ToastUtil.getToastUtil().showShort(getString(R.string.pay_success));

            RxBus.getDefault().post("confim_success");
        }
        payChoseDialog.dismiss();
    }
}
